package xiao.ze.demo.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xiao.ze.demo.entity.Course;
import xiao.ze.demo.entity.SelCourseTerm;
import xiao.ze.demo.service.impl.CourseServiceImpl;
import xiao.ze.demo.service.impl.CourseTypeServiceImpl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * @description: TODO
 * @author: Tokyo_God
 * @date: 2021/2/14 14:29
 * Role of:
 * @version: v1.0
 */
@Controller
@RequestMapping("/course")
@SessionAttributes(value = {"user", "page"})//myClick没用
public class CourseController {

    @Resource
    CourseTypeServiceImpl courseTypeService;

    @Resource
    CourseServiceImpl courseService;

    /**
     * 进入新增课程(开课登记)
     *
     * @return
     */
    @GetMapping("/input_course")
    public String input_course(Model model) {
        model.addAttribute("courseTypeList", courseTypeService.selAllCourseType());
        return "/course/input_course";
    }

    /**
     * 进入课程管理
     *
     * @return
     */
    @RequestMapping("/list_course")
    public String list_course(Model model, @RequestParam(required = false, defaultValue = "1") Integer pageNum, @RequestParam(required = false, defaultValue = "8") Integer pageSize, SelCourseTerm courseTerm) {
        System.out.println(courseTerm.toString());
        System.out.println(pageNum);
        PageHelper.startPage(pageNum, pageSize);
        List<Course> courses = courseService.selCourse(courseTerm);
        for (Course c : courses) {
            System.out.println(c.getTextbookPic());
        }
        PageInfo pageInfo = new PageInfo(courses);
        model.addAttribute("page", pageInfo);
        model.addAttribute("courseTypeList", courseTypeService.selAllCourseType());
        model.addAttribute("courseTypeMap", courseTypeService.selAllCourseTypeMap());

//        byte[] b=courses.get(0).getTextbookPic();
//        System.out.println(b);
//        model.addAttribute("image",new String(b));
//        model.addAttribute("ptButtonPic", "<img src='"+(new String(b))+"' style='margin-top:5%;display: block;width:100px;height:100px'>");
        return "/course/list_course";
    }

    /**
     * 查看课程编号是否重复
     *
     * @param no
     * @return
     */
    @GetMapping("/selCourseNo/{no}")
    @ResponseBody
    public String selCourseNo(@PathVariable("no") String no) {
        String str = "";
        Course course = courseService.selCourseNo(no);
        System.out.println(course == null);
        if (course != null) {
            str = "课程编号重复";
        }
        return str;
    }

    /**
     * 新增课程
     *
     * @param course
     * @param model
     * @return
     */
    @PostMapping("/create")
    public String create(Course course, @RequestParam(value = "coursetextbookpic") MultipartFile file, String[] courseReqs, Model model) {
        System.out.println("新增课程");
        String reqs = "";
        for (int i = 0; i < courseReqs.length; i++) {
            reqs += courseReqs[i];
            if (i < courseReqs.length - 1) {
                reqs += "|";
            }
        }
        course.setReqs(reqs);
        try {
//            if (null!=file){//&&file.getBytes()
//                System.out.println(file.getBytes());
//            }

            InputStream ins = file.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = ins.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.flush();
            byte data[] = bos.toByteArray();
            if (data.length == 0) {
                InputStream pngInStream =
                        Thread.currentThread().getContextClassLoader()
                                .getResourceAsStream("static/pics/SpringBoot.png");
//              this.getClass().getClassLoader().getResourceAsStream("static/pics/logout.jpg");
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                buffer = new byte[1024];
                while ((len = pngInStream.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.flush();
                data = out.toByteArray();
            }
            course.setTextbookPic(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(course.toString());
        int num = courseService.addCourse(course);
        String str = "添加失败";
        if (num > 0) {
            str = "添加成功";
            System.out.println("添加成功");
        }
//        return "redirect:/course/input_course";
        model.addAttribute("courseTypeList", courseTypeService.selAllCourseType());
        model.addAttribute("error", str);
        return "/course/input_course";
    }


    @RequestMapping("/getPic/{courseNo}")
    public void getPic(@PathVariable("courseNo") String no, HttpServletResponse response) {
        System.out.println("getPic----------------------------------");
//        System.out.println(textbookPic);
//        List<Course> courses

        Course course = courseService.selCourseNo(no);
        byte[] data = course.getTextbookPic();
        //向浏览器发通知  我要发送的是图片
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputSream = null;
        try {
            outputSream = response.getOutputStream();
            outputSream.write(data);
            outputSream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 删除课程
     *
     * @param no
     * @return
     */
    @DeleteMapping("/remove/{courseNo}")
    public String remove(@PathVariable("courseNo") String no) {
        courseService.delCourse(no);
        return "redirect:/course/list_course";
    }

    /**
     * 进入修改页面
     *
     * @param no
     * @param model
     * @return
     */
    @GetMapping("/preUpdate/{courseNo}")
    public String preUpdate(@PathVariable("courseNo") String no, Model model) {
        Course course = courseService.selCourseNo(no);
        model.addAttribute("course", course);
        model.addAttribute("courseTypeList", courseTypeService.selAllCourseType());
        return "/course/update_course";
    }


    /**
     * 修改页面
     *
     * @return
     */
    @PostMapping("/update")
    public String update(Course course, MultipartFile coursetextbookpic, String[] courseReqs) {
        System.out.println("修改课程");
        if (courseReqs != null && courseReqs.length > 0) {
            String reqs = "";
            for (int i = 0; i < courseReqs.length; i++) {
                reqs += courseReqs[i];
                if (i < courseReqs.length - 1) {
                    reqs += "|";
                }
            }
            course.setReqs(reqs);
        }
        if (coursetextbookpic != null) {
            try {
                InputStream ins = coursetextbookpic.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                while ((len = ins.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                bos.flush();
                byte data[] = bos.toByteArray();
                if (data.length > 0) {
                    course.setTextbookPic(data);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(course.toString());
        courseService.upCourse(course);
        return "redirect:/course/list_course";
    }


}
